<template>
  <div class="house-list-container">
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h1>房源列表</h1>
      <el-button size="medium" type="primary" @click="handleAddHouse"
        >添加房源</el-button
      >
    </div>
    <el-table :data="currentPageData" style="width: 100%">
      <el-table-column label="图片" width="150">
        <template #default="scope">
          <img
            v-if="scope.row.images && scope.row.images.length > 0"
            :src="scope.row.images[0]"
            alt="房屋图片"
            style="max-width: 100%; height: auto"
          />
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="基本信息" width="400">
        <template #default="scope">
          <p>
            <strong>{{ getBasicInfo(scope.row) }}</strong>
          </p>
          <p>{{ getRoomConfig(scope.row) }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="monthRent" label="月租金" width="120">
        <template #default="scope"> {{ scope.row.monthRent }} 元 </template>
      </el-table-column>
      <el-table-column label="联系人信息" width="200">
        <template #default="scope">
          {{ getContactInfo(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusTag(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 1"
            size="small"
            type="warning"
            @click="handleUnlist(scope.$index, scope.row)"
            >下架</el-button
          >
          <el-button
            v-if="scope.row.status !== 2"
            size="small"
            type="primary"
            @click="navigateToUpdateHouse(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.status === 3"
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="totalRecords"
      :page-size="pageSize"
      v-model:current-page="currentPage"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: center"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import {
  ElTable,
  ElTableColumn,
  ElTag,
  ElButton,
  ElMessageBox,
  ElMessage,
  ElPagination,
} from "element-plus";
import api from "@/api";
import { useUserStore } from "@/stores/user";
import { useRouter } from "vue-router";

const userStore = useUserStore();
const router = useRouter();

const houseList = ref([]);
const totalRecords = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

onMounted(async () => {
  await fetchHouses();
});

const fetchHouses = async () => {
  try {
    const response = await api.house.getHousesByOwnerId(userStore.userInfo.id);
    console.log("获取房屋列表成功:", response.data);

    // 处理图片 URL
    houseList.value = response.data.map((data) => ({
      ...data,
      images: data.houseImageList.map((img) => `http://localhost:8080${img}`),
    }));
    totalRecords.value = houseList.value.length;
  } catch (error) {
    console.error("获取房屋列表失败:", error);
    ElMessage.error("获取房屋列表失败");
  }
};

const filteredHouseList = computed(() => {
  return houseList.value.filter(
    (house) => house.ownerId === userStore.userInfo.id && house.status !== -1
  );
});

const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredHouseList.value.slice(start, end);
});

const getStatusText = (status) => {
  switch (status) {
    case 1:
      return "未租出";
    case 2:
      return "已租出";
    case 3:
      return "已下架";
    case -1:
      return "已删除";
    case -2:
      return "待审核";
    case -3:
      return "审核不通过";
    default:
      return "未知";
  }
};

const getStatusTag = (status) => {
  switch (status) {
    case 1:
      return "info"; // 未租出
    case 2:
      return "success"; // 已租出
    case 3:
      return "warning"; // 已下架
    case -1:
      return "danger"; // 已删除
    case -2:
      return "warning"; // 待审核
    case -3:
      return "danger"; // 审核不通过
    default:
      return ""; // 未知
  }
};

const getRoomConfig = (row) => {
  return `${row.bedroom}室${row.livingRoom}厅${row.kitchen}厨${row.toilet}卫`;
};

const getBasicInfo = (row) => {
  const rentTypeLabel = row.rentType === "whole" ? "整租" : "合租";
  return `${rentTypeLabel} | ${row.direction} | ${row.title} | ${row.city} | ${row.address}`;
};

const getContactInfo = (row) => {
  return `${row.contactName} | ${row.contactPhone}`;
};

const navigateToUpdateHouse = (id) => {
  router.push({ name: "UpadteHouse", params: { id } });
};

const handleDelete = (index, row) => {
  ElMessageBox.confirm("此操作将永久删除该房源, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteHouse(row.id);
      houseList.value.splice(index, 1);
      ElMessage.success("删除成功!");
      //刷新页面
      location.reload();
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleUnlist = (index, row) => {
  ElMessageBox.confirm("此操作将下架该房源, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      unlistHouse(row.id);
      row.status = 3;
      ElMessage.success("房源已下架!");
    })
    .catch(() => {
      ElMessage.info("已取消下架");
    });
};

const updateHouse = async (id, data) => {
  try {
    await api.house.updateHouse(id, data);
  } catch (error) {
    console.error("更新房屋信息失败:", error);
    ElMessage.error("更新房屋信息失败");
  }
};

const deleteHouse = async (id) => {
  try {
    await api.house.updateStatus(id, -1);
    console.log("房屋已删除:", id);
  } catch (error) {
    console.error("删除房屋失败:", error);
    ElMessage.error("删除房屋失败");
  }
};

const unlistHouse = async (id) => {
  try {
    await api.house.updateStatus(id, 3);
    console.log("房屋已下架:", id);
  } catch (error) {
    console.error("下架房屋失败:", error);
    ElMessage.error("下架房屋失败");
  }
};

const handlePageChange = (newPage) => {
  console.log("New Page:", newPage); // 打印当前页码
  currentPage.value = newPage;
};

const handleAddHouse = () => {
  router.push({ name: "AddHouse" });
};
</script>

<style scoped lang="css">
.house-list-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

h1 {
  color: #333;
  margin-bottom: 20px;
}

.el-table {
  width: 100%;
  border-radius: 8px;
}

.el-table th.is-leaf {
  background-color: #f0f9eb;
}

.el-table::before {
  height: 0;
}
</style>
